package com.wgd.mqttandroidwgd;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String topic = "device/{uuid}/electronic/command";

        MQTTHelper mqttHelper = new MQTTHelper(this, "ws://www2.cjbeidou.com:80/mqtt", null, null);
        mqttHelper.connect(topic, true, new MqttCallback() {
            @Override
            public void connectionLost(Throwable throwable) {

            }

            @Override
            public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
                //收到消息
                Toast.makeText(MainActivity.this, new String(mqttMessage.getPayload()), Toast.LENGTH_SHORT).show();
                Log.e("aaa", "消息：" + new String(mqttMessage.getPayload()));
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
                Log.e("aaa","发送成功");
            }
        });
        Button tvSend = findViewById(R.id.tv_send);
        EditText etMsg = findViewById(R.id.et_msg);
        tvSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //发送消息
                mqttHelper.publish(topic, etMsg.getText().toString());
            }
        });
    }

}